package com.googlecode.animator.controller
{
	
	import com.googlecode.data.ProjectConstants;
	import com.googlecode.data.materials.FileAssetMaterialVO;
	import com.googlecode.data.materials.MaterialVO;
	import com.googlecode.data.objects3d.MaterialsListObject3DVO;
	import com.googlecode.data.objects3d.Object3DVO;
	import com.googlecode.data.objects3d.SingleMaterialObject3DVO;
	
	import flash.filesystem.File;
	import flash.utils.Dictionary;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
			
	public class MakeFilePathsAbsoluteCommand extends BaseCommand
	{
		/**
		 * Executes command. 
		 * @param notification
		 * 
		 */
		override public function execute(notification:INotification):void
		{
			super.execute(notification);
			
			for each(var object3D:Object3DVO in settings.objects3D)
			{
				if(object3D is SingleMaterialObject3DVO)
				{
					handleSingleMaterial((object3D as SingleMaterialObject3DVO).material);
				}
				
				if(object3D is MaterialsListObject3DVO)
				{
					handleMaterialsList((object3D as MaterialsListObject3DVO).materialsList);
				}
			}
				
		}
		
		protected function handleSingleMaterial(mat:MaterialVO):void
		{
			if(mat is FileAssetMaterialVO)
			{
				//var filePath:String = (mat as FileAssetMaterialVO).filePath;
				convertPath(mat as FileAssetMaterialVO);
			}
			
		}
		
		protected function handleMaterialsList(matList:Dictionary):void
		{
			for each(var mat:MaterialVO in matList)
			{
				if(mat is FileAssetMaterialVO)
				{
					//var filePath:String = (mat as FileAssetMaterialVO).filePath;
					convertPath(mat as FileAssetMaterialVO);
				}
			}
		}
		
		protected function convertPath(mat:FileAssetMaterialVO):void
		{	
			var file:File;
			var path:String;
			var length:uint = ProjectConstants.APPLICATION_ASSETS_DIRECTORY.length;
			
			if(mat.isRelative && mat.filePath.substr(0, length)!= ProjectConstants.APPLICATION_ASSETS_DIRECTORY)
			{
				try
				{
					file = new File()
					file.url = settings.savePath;
					
					file = file.parent;
					
					
					path = file.url + "/" + mat.filePath;
					
					mat.filePath = path;
					mat.isRelative = false;
					
				}catch(err:Error)
				{
					trace("Cannot determine parent directory \n" + err);
				}
								
			}
		}
	}
}